﻿using System;
using System.ComponentModel;
using System.Web.UI;

namespace Guru.Web.Controls.Validators
{
    public class CompareValidationItem: ValidationItem
    {
        #region const
        protected const string _JS_MESSAGE = "{0}: \"{1}\"";
        protected const string _JS_RULE_NAME = "equalTo";

        /// <summary>
        /// Add equalTo rule
        ///     {0}: CLientId of the control
        ///     {1}: Name of the rule
        ///     {2}: ClientId of the control to compare
        ///     {2}: Custom message
        /// </summary>
        protected const string _JS_RULE = @"
            if($('#{0}') != null)
                $('#{0}').rules('add', [OPEN]
                    {1}: '#{2}',
                     messages: [OPEN]
                        {3}
                    [CLOSE]
                [CLOSE]); 
                ";
        #endregion

        #region Redering
        public override string RenderTrigger(HtmlTextWriter writer)
        {
            return string.Empty;
        }

        public override string RenderRuleRegister(HtmlTextWriter writer)
        {  
            string message = string.Empty;
            if (string.IsNullOrEmpty(this.Message) == false)
                message = string.Format(_JS_MESSAGE, _JS_RULE_NAME, this.Message);

            string basicRule = string.Format(_JS_RULE,
                this.ObjectControlToValidate.ToJQueryId(), _JS_RULE_NAME,
                this.ObjectControlToCompare.ToJQueryId(),
                message);
            return basicRule.ReplaceTag();
        }
        #endregion

        [Category("Behavior"), DefaultValue(""),
        Description("Identity of the control to compare"), NotifyParentProperty(true)]
        public string ControlToCompare
        {
            set
            {
                ViewState["ControlToCompare"] = value;
            }
            get
            {
                return (string)ViewState["ControlToCompare"];
            }
        }

        protected Control ObjectControlToCompare
        {
            get
            {

                if (string.IsNullOrEmpty(this.ControlToCompare))
                    throw new PropertyNullRefException("ControlToCompare");
                Control container = this.Container.Parent;
                Control ctr = this.FindControl(container, this.ControlToCompare);
                if (ctr == null)
                    throw new ControlNotFoundException("ControlToCompare: "+this.ControlToCompare);
                else
                    return ctr;
            }
        }
    }
}
